using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Common;

using SqlWebAdmin.CSharp;

public partial class RenameTable : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            txtTableName.Text = Request.QueryString["table"];
        }
    }

    protected void cmdRename_Click(object sender, EventArgs e)
    {
       
            lblError.Visible = false;

			Server smoServer = SmoHelper.GetServer();
            try
            {
               

                string databaseName = Request.QueryString["database"];
                Database smoDatabase = smoServer.Databases[databaseName];
                if (smoDatabase != null)
                {

                    string tableName = Request.QueryString["table"];
                    string tableSchema = Request.QueryString["schema"];

                    Microsoft.SqlServer.Management.Smo.Table smoTable = smoDatabase.Tables[tableName, tableSchema];
                    if (smoTable != null)
                    {
                        smoTable.Rename(txtTableName.Text);

                        Response.Redirect("Tables.aspx?database=" + HttpUtility.UrlEncode(Request.QueryString["database"]), false);
                    }
                    else
                    {
                        Response.Redirect(String.Format("error.aspx?error={0}", Globals.tableNotFoundErrorNumber), false);
                    }
                }
                else
                {
                    Response.Redirect(String.Format("error.aspx?error={0}", Globals.databaseNotFoundErrorNumber), false);
                }
            }
            catch (SmoException smoEx)
            {
                lblError.Text = HttpUtility.HtmlEncode(Common.ConcatenateExceptions(smoEx));
                lblError.Visible = true;
            }
            catch (System.Exception ex)
            {
                lblError.Text = HttpUtility.HtmlEncode(Common.ConcatenateExceptions(ex));
                lblError.Visible = true;
            }

        
    }

    protected void cmdCancel_Click(object sender, EventArgs e)
    {
        Response.Redirect(String.Format("Tables.aspx?database={0}", Server.UrlEncode(Request.QueryString["database"])), false);
    }


}
